import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split

# 生成数据
X, y, true_coef = make_regression(n_samples=100, n_features=10,
                                  n_informative=5, noise=10,
                                  coef=True, random_state=42)

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

from sklearn.linear_model import Lasso, LassoCV
from sklearn.metrics import mean_squared_error, r2_score

# 使用 LassoCV 自动选择最优的 alpha
lasso_cv = LassoCV(alphas=np.logspace(-4, 4, 20), cv=5, random_state=42)
lasso_cv.fit(X_train, y_train)

# 输出最优的 alpha
print(f"最优的 alpha 值: {lasso_cv.alpha_:.4f}")

# 使用最优的 alpha 训练 Lasso 模型
lasso = Lasso(alpha=lasso_cv.alpha_)
lasso.fit(X_train, y_train)

# 模型评估
y_pred = lasso.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)

print(f"测试集的均方误差 (MSE): {mse:.2f}")
print(f"测试集的 R² 分数: {r2:.2f}")
